package com.bobo.gmall.realtime.app.dwd;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bobo.gmall.realtime.utils.MyKafkaUtil;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;


//数据流：web/app -> Nginx -> SpringBoot -> Kafka(ods) -> FlinkApp -> Kafka(dwd)
//程  序：mocklog -> Nginx -> Logger.sh -> Kafka(ZK) -> BaseLogApp -> Kafka
public class BaseLogApp {

    public static void main(String[] args) throws Exception {

        //TODO 1.获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

//        env.setStateBackend(new FsStateBackend("hdfs://192.168.45.132:9000/gmall-flink/ck"));
//        env.enableCheckpointing(5000L);   // 即5s触发一次checkPoint
//        env.getCheckpointConfig().setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE);  // 模式
//        env.getCheckpointConfig().setAlignmentTimeout(10000L);   // 超时时间 10s
//        env.getCheckpointConfig().setMaxConcurrentCheckpoints(2);    //
//        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(3000);   // 两次checkpoint间最小间隔时间
//        //env.setRestartStrategy(RestartStrategies.fixedDelayRestart());  老版本需要注意

        //TODO 2.消费ods_base_log主题数据，创建流
        String sourceTopic = "ods_base_log";
        String groupId = "base_log_app";
        DataStreamSource<String> kafkaDS = env.addSource(MyKafkaUtil.getKafkaConsumer(sourceTopic, groupId));

        //TODO 3.将每行数据转为json对象
//        kafkaDS.map(JSON::parseObject);  //简写
//        kafkaDS.map(line -> {
//            return JSON.parseObject(line);
//        });

        OutputTag<String> outputTag = new OutputTag<String>("Dirty"){};
        SingleOutputStreamOperator<JSONObject> jsonObjDS = kafkaDS.process(new ProcessFunction<String, JSONObject>() {
            @Override
            public void processElement(String value, Context context, Collector<JSONObject> collector) throws Exception {
                try {
                    JSONObject jsonObject = JSONObject.parseObject(value);
                    collector.collect(jsonObject);
                } catch (Exception e) {
                    //发生异常，将数据写入侧输出流
                    context.output(outputTag, value);
                }
            }
        });

        //打印脏数据
        jsonObjDS.getSideOutput(outputTag).print("Dirty>>>>>>>>>>>>");


        //TODO 4.新老用户校验（状态编程）
        SingleOutputStreamOperator<JSONObject> jsonObjWithNewFlagDS = jsonObjDS.keyBy(jsonObj -> jsonObj
                .getJSONObject("common").getString("mid"))
                .map(new RichMapFunction<JSONObject, JSONObject>() {

                    private ValueState<String> valueState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        valueState = getRuntimeContext().getState(new ValueStateDescriptor<String>(
                                "value-state", String.class));
                    }

                    @Override
                    public JSONObject map(JSONObject value) throws Exception {

                        //获取数据中的is_new标记
                        String isNew = value.getJSONObject("common").getString("is_new");

                        //判断isNew标记是否为1
                        if ("1".equals(isNew)) {
                            String state = valueState.value();
                            if (state != null) {
                                //修改isNew标记
                                value.getJSONObject("common").put("is_new", "0");
                            } else {
                                valueState.update("1");
                            }
                        }
                        return value;
                    }


                });

        //TODO 5.分流  -->  ①页面：主流  ②启动：侧输出流  ③曝光：侧输出流
        OutputTag<String> startOutputTag = new OutputTag<String>("start"){};
        OutputTag<String> displayOutputTag = new OutputTag<String>("display"){};
        SingleOutputStreamOperator<String> pageDS = jsonObjWithNewFlagDS.process(new ProcessFunction<JSONObject, String>() {
            @Override
            public void processElement(JSONObject value, Context context, Collector<String> collector) throws Exception {

                //获取启动日志字段
                String start = value.getString("start");
                if (start != null && start.length() > 0) {
                    //将数据写入启动日志侧输出流
                    context.output(startOutputTag, value.toJSONString());
                } else {
                    //将数据写入页面日志主流
                    collector.collect(value.toJSONString());

                    //取出数据中的曝光数据
                    JSONArray displays = value.getJSONArray("displays");
                    if (displays != null && displays.size() > 0) {

                        //获取页面ID
                        String pageId = value.getJSONObject("page").getString("page_id");

                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);

                            //添加页面id
                            display.put("page_id", pageId);

                            //将输出写出到曝光侧输出流
                            context.output(displayOutputTag, display.toJSONString());
                        }
                    }
                }
            }
        });

        //TODO 6.提取侧输出流
        DataStream<String> startDS = pageDS.getSideOutput(startOutputTag);
        DataStream<String> displayDS = pageDS.getSideOutput(displayOutputTag);

        //TODO 7.将3个流进行打印并输出到对应的Kafka主题中
        startDS.print("start>>>>>>>>>>>>>>>");
        pageDS.print("page>>>>>>>>>>>>>>>>>");
        displayDS.print("display>>>>>>>>>>>>>>>");

        startDS.addSink(MyKafkaUtil.getKafkaProducer("dwd_start_log"));
        pageDS.addSink(MyKafkaUtil.getKafkaProducer("dwd_page_log"));
        displayDS.addSink(MyKafkaUtil.getKafkaProducer("dwd_display_log"));

        //TODO 8.启动任务
        env.execute("BaseLogApp");


        };
    }
